package com.ruoyi.user.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.service.impl.MessageServiceImpl;
import com.ruoyi.user.service.impl.UserServiceImpl;
import com.ruoyi.user.websocket.WebSocketUsers;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.websocket.*;
import java.util.*;
import java.io.IOException;

/**
 * @author ffc
 * @version 1.0
 * @description: TODO
 * @className: RabbitMQListener
 * @date 2024/8/26 21:49
 */

@Component
public class UserQueueListener {

    @Autowired
    private UserServiceImpl userServiceImpl;

    @Autowired
    private MessageServiceImpl messageServiceImpl;

    @RabbitListener(queues = "user_queue")
    public void listenerUserQueue(Message message) throws IOException {
        try {
            SysNotice sysNotice = JSON.parseObject(message.getBody(), SysNotice.class);
            List<User> users = userServiceImpl.list();
            List<com.ruoyi.user.api.domain.Message> messages = new ArrayList<>();
            for (User user :users) {
                messages.add(new com.ruoyi.user.api.domain.Message(user.getId(),sysNotice.getNoticeTitle(),
                        sysNotice.getNoticeContent(),"1",new Date()));
            }
            messageServiceImpl.saveBatch(messages);
            Map<String, Session> map = WebSocketUsers.getUsers();
            Set<String> keys = map.keySet();
            if(keys==null||keys.size()==0){
                return;
            }
            for (String item:keys) {
                Session session = map.get(item);
                WebSocketUsers.sendMessageToUserByText(session, new String(message.getBody()));
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
